/**
 * Created Date: Friday, October 21st 2022, 10:30:24 pm
 * Author: CodingGorit
 * -----
 * Last Modified: Fri Oct 28 2022
 * Modified By: CodingGorit
 * -----
 * Copyright (c) 2022 fmin-courses
 * ------------------------------------
 * Javascript will save your soul!
 */

import log from "../utils/log";
import query from "../utils/DBUtils";
import { IStudent } from "../models";

const TAG = "ExampleService"
const database = "studentmanagementsystem";
const querySql = {
    baseSelect: `select stuId, stuName, stuAge, classz from ${database}.student `
}

// 数据结构，与数据库中的表对应

// Example 查询学生信息
export const getStudents = async (params?: object) => {
    // params 判空

    // dev 环境的 dbConfig 并没有指定对应的 数据库，所以查询需要把 数据库名加上
    let sql = querySql.baseSelect;

    // 根据 params 进行 sql 的拼接

    // 由于返回的是 Promise，这里需要使用 async 和 await 将异步变成同步 拿到数据
    const result = await query(sql);
    return result;
}

// Example 根据 ID 查询学生信息，写法二，使用异步传参 【推荐】
export const getStudentById = (id: number, callback = (val: any, msg?: string) => {}) =>{
    if (id < 0 || !id) {
        id = 0;
    }

    let sql = querySql.baseSelect + `where stuId = ${id} limit 1`;

    query(sql).then(result => {
        log.info(`${TAG} query result is => ${result}, type ${typeof result}`);
        if (Array.isArray(result) && result.length > 0) {
            callback(result);
        } else {
            log.info(`${TAG} query result is empty`);
            callback(0, "Student not found!");
        }
    }).catch(err => {
        log.error(err);
        callback(0);
    });
}


// Example 新增一条学生信息
export const addStudent = (body: IStudent) => {

}


// Example 根据 ID 删除
export const delStudentById = (id: number) => {

}

// Example 更新一条数据
export function updateStudent(student: IStudent) {

}